<template>
  <view class="asset-edit-container">
    <text class="page-title">编辑资产</text>

    <!-- 加载提示 -->
    <view class="loading" v-if="!loaded">
      <text>正在加载...</text>
    </view>

    <view class="form card" v-if="loaded">
      <!-- 复用新增资产布局，双向绑定同名字段 -->
      <view class="field"><text class="label">资产编号</text><input class="input" v-model="form.assetNo" /></view>
      <view class="field"><text class="label">设备名称</text><input class="input" v-model="form.assetName" /></view>
      <view class="field"><text class="label">设备号</text><input class="input" v-model="form.deviceNo" /></view>
      <view class="field"><text class="label">规格型号</text><input class="input" v-model="form.modelNo" /></view>
      <view class="field"><text class="label">品牌</text><input class="input" v-model="form.brand" /></view>
      <view class="field"><text class="label">制造商</text><input class="input" v-model="form.manufacturer" /></view>
      <view class="field"><text class="label">位置</text><input class="input" v-model="form.location" /></view>
      <view class="field"><text class="label">使用部门</text><input class="input" v-model="form.deptName" /></view>
      <view class="field"><text class="label">供应商</text><input class="input" v-model="form.supplierName" /></view>

      <view class="field"><text class="label">设备类型</text>
        <picker mode="selector" :range="deviceTypes" range-key="name" @change="onTypeChange">
          <view class="input picker">{{ typeName || '请选择设备类型' }}</view>
        </picker>
      </view>
      <view class="field"><text class="label">状态</text>
        <picker mode="selector" :range="statusList" range-key="name" @change="onStatusChange">
          <view class="input picker">{{ statusName || '请选择状态' }}</view>
        </picker>
      </view>

      <view class="field"><text class="label">购入日期</text>
        <picker mode="multiSelector" :range="dateTimeRange" :value="purchaseDateIdx" @change="onPickPurchaseDate">
          <view class="input picker">{{ form.purchaseDate || 'YYYY-MM-DD HH:mm:ss' }}</view>
        </picker>
      </view>
      <view class="field"><text class="label">投产日期</text>
        <picker mode="multiSelector" :range="dateTimeRange" :value="prodDateIdx" @change="onPickProdDate">
          <view class="input picker">{{ form.commissioningDate || 'YYYY-MM-DD HH:mm:ss' }}</view>
        </picker>
      </view>

      <button class="submit" @click="submit">保存</button>
    </view>
  </view>
</template>

<script>
import assetApi from '@/api/asset/asset.js'
import { listDeviceType } from '@/api/dict/deviceType.js'
import { getDicts } from '@/api/dict/data.js'
export default {
  data(){
    return{loaded:false, form:{}, deviceTypes:[], statusList:[], typeName:'', statusName:'', dateTimeRange:[], purchaseDateIdx:[0,0,0,0,0,0], prodDateIdx:[0,0,0,0,0,0]}
  },
  async onLoad(q){
    console.log('编辑页面 onLoad 参数:', q)
    this.initDateTime()
    // 先加载元数据，再加载资产详情，确保依赖关系正确
    await this.loadMeta()
    if (q && q.assetNo) {
      await this.loadDetail(q.assetNo)
    } else {
      // 如果没有 assetNo，显示空表单让用户填写
      this.form = {
        assetNo: '', assetName: '', deviceNo: '', modelNo: '', brand: '', manufacturer: '',
        location: '', deptName: '', supplierName: '', equipmentTypeCode: '', statusCode: '',
        purchaseDate: '', commissioningDate: '', imageUrls: []
      }
      this.loaded = true
      console.log('没有 assetNo 参数，显示空表单')
    }
  },
  methods:{
    async loadDetail(assetNo){
      try{
        console.log('开始加载资产详情，assetNo:', assetNo)
        const res = await assetApi.getAsset(assetNo)
        const d = res.data || res
        console.log('加载到的资产数据:', d)
        this.form={
          assetNo:d.assetNo, assetName:d.assetName, deviceNo:d.deviceNo, modelNo:d.modelNo, brand:d.brand, manufacturer:d.manufacturer, location:d.location,
          deptName:d.deptName, supplierName:d.supplierName, equipmentTypeCode:d.equipmentTypeCode, statusCode:d.statusCode,
          purchaseDate:d.purchaseDate, commissioningDate:d.commissioningDate,
          imageUrls: typeof d.imageUrls==='string'? JSON.parse(d.imageUrls||'[]'): (d.imageUrls||[])
        }
        // 显示文本
        const t=this.deviceTypes.find(v=>v.code===this.form.equipmentTypeCode); this.typeName=t?t.name:''
        const s=this.statusList.find(v=>v.code===this.form.statusCode); this.statusName=s?s.name:''

        // 设置日期选择器索引
        if (this.form.purchaseDate) {
          this.purchaseDateIdx = this.parseDateToIndex(this.form.purchaseDate)
        }
        if (this.form.commissioningDate) {
          this.prodDateIdx = this.parseDateToIndex(this.form.commissioningDate)
        }

        this.loaded=true
        console.log('资产数据加载完成，设置 loaded=true')
      }catch(e){
        console.error('加载资产详情失败:', e)
        uni.showToast({title:'加载失败',icon:'none'})
        this.loaded = true // 即使加载失败也要显示表单，避免页面空白
      }
    },
    async loadMeta(){
      try{
        console.log('开始加载元数据')
        const r=await listDeviceType({})
        const rows=r.rows||r.data||[]
        this.deviceTypes=rows.map(x=>({code:x.code||x.id||'',name:x.name||x.typeName||''}))
        console.log('加载设备类型完成:', this.deviceTypes.length, '个')
      }catch(e){
        console.error('加载设备类型失败:', e)
      }

      try{
        const r=await getDicts('asset_status')
        const arr=r.data||r||[]
        this.statusList=arr.map(d=>({code:d.dictValue,name:d.dictLabel}))
        console.log('加载状态列表完成:', this.statusList.length, '个')

        // 如果已经加载了资产数据，需要重新设置显示文本
        if (this.loaded && this.form.equipmentTypeCode) {
          const t=this.deviceTypes.find(v=>v.code===this.form.equipmentTypeCode)
          this.typeName=t?t.name:''
          console.log('重新设置设备类型显示:', this.typeName)
        }
        if (this.loaded && this.form.statusCode) {
          const s=this.statusList.find(v=>v.code===this.form.statusCode)
          this.statusName=s?s.name:''
          console.log('重新设置状态显示:', this.statusName)
        }
      }catch(e){
        console.error('加载状态列表失败:', e)
      }
    },
    initDateTime(){ const years=[],months=[],days=[],hours=[],minutes=[],seconds=[]; const now=new Date(); const y0=now.getFullYear()-3; for(let y=y0;y<=y0+6;y++) years.push(String(y)); for(let m=1;m<=12;m++) months.push(String(m).padStart(2,'0')); for(let d=1;d<=31;d++) days.push(String(d).padStart(2,'0')); for(let h=0;h<24;h++) hours.push(String(h).padStart(2,'0')); for(let i=0;i<60;i++){minutes.push(String(i).padStart(2,'0'));seconds.push(String(i).padStart(2,'0'))} this.dateTimeRange=[years,months,days,hours,minutes,seconds] },
    onTypeChange(e){ const it=this.deviceTypes[Number(e.detail.value)]; if(it){ this.form.equipmentTypeCode=it.code; this.typeName=it.name } },
    onStatusChange(e){ const it=this.statusList[Number(e.detail.value)]; if(it){ this.form.statusCode=it.code; this.statusName=it.name } },
    onPickPurchaseDate(e){ const [y,m,d,h,i,s]=this.pick(e.detail.value); this.purchaseDateIdx=e.detail.value; this.form.purchaseDate=`${y}-${m}-${d} ${h}:${i}:${s}` },
    onPickProdDate(e){ const [y,m,d,h,i,s]=this.pick(e.detail.value); this.prodDateIdx=e.detail.value; this.form.commissioningDate=`${y}-${m}-${d} ${h}:${i}:${s}` },
    pick(idx){ const a=v=>Number(v||0); const y=this.dateTimeRange[0][a(idx[0])],m=this.dateTimeRange[1][a(idx[1])],d=this.dateTimeRange[2][a(idx[2])],h=this.dateTimeRange[3][a(idx[3])],i=this.dateTimeRange[4][a(idx[4])],s=this.dateTimeRange[5][a(idx[5])]; return [y,m,d,h,i,s] },
    parseDateToIndex(dateStr){
      try {
        const date = new Date(dateStr)
        const y0 = new Date().getFullYear() - 3
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()

        return [
          year - y0, // 年索引
          month - 1, // 月索引 (0-11)
          day - 1,   // 日索引 (0-30)
          hour,      // 时索引 (0-23)
          minute,    // 分索引 (0-59)
          second     // 秒索引 (0-59)
        ]
      } catch(e) {
        console.warn('日期解析失败:', dateStr, e)
        return [0,0,0,0,0,0] // 返回默认索引
      }
    },
    async submit(){
      if(!this.form.equipmentTypeCode) return uni.showToast({title:'请选择设备类型',icon:'none'})
      if(!this.form.statusCode) return uni.showToast({title:'请选择状态',icon:'none'})
      const payload={...this.form,imageUrls:JSON.stringify(this.form.imageUrls||[])}
      try{
        // 注意：需要添加更新资产的 API 方法，这里暂时使用 put 方法
        const { put } = await import('@/utils/request')
        const r = await put('/system/asset', payload)
        if(r && (r.code===undefined || r.code===200)){ uni.showToast({title:'保存成功',icon:'success'}); setTimeout(()=>uni.navigateBack({delta:1}),600) } else { uni.showToast({title:r.msg||'保存失败',icon:'none'}) }
      }catch(e){ uni.showToast({title:'保存失败',icon:'none'}) }
    }
  }
}
</script>

<style>
.asset-edit-container{min-height:100vh;background:#f6f7fb}
.page-title{display:block;padding:24rpx 24rpx 8rpx;font-size:40rpx;font-weight:700;color:#111}
.loading{display:flex;justify-content:center;align-items:center;padding:100rpx;color:#666;font-size:28rpx}
.card{margin:16rpx;border-radius:16rpx;background:#fff;box-shadow:0 6rpx 20rpx rgba(0,0,0,.06)}
.form{padding:24rpx}
.field{margin-bottom:28rpx}
.label{display:block;color:#666;margin-bottom:10rpx;font-size:26rpx}
.input{border:1rpx solid #e5e5e5;border-radius:12rpx;padding:18rpx;background:#fafafa}
.picker{color:#333}
.submit{margin-top:24rpx;background:#007aff;color:#fff}
</style>

